<?php

namespace App\Http\Controllers\Api\V1;

use App\B2BProject\Custom\Business\Store;
use App\B2BProject\Custom\Member;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StoreController extends Controller
{
    /**
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index(Request $request)
    {
        $providers = Member::selectProvider()->whereHas('store', function ($q) {
            $q->withLogo();
        });

        if ($name = $request->query('name')) {
            $providers->whereHas('information', function ($query) use ($name) {
                $query->where('company', 'like', "%$name%");
            });
        }

        if ($classId = $request->query('class_id')) {
            $providers->whereHas('store.mainCategory', function ($query) use ($classId) {
                $query->whereIn('id', (array)$classId);
            });
        }

        $collection = $providers->orderBy('created_at', 'desc')->get();

        $data = [];

        foreach ($collection as $provider) {
            $data[] = [
                'id'          => $provider->id,
                'name'        => $provider->information->company,
                'category'    => call_user_func(function (Member $provider) {
                    $data = [];
                    if ($categories = $provider->store->mainCategory) {
                        foreach ($categories as $category) {
                            $data[] = [
                                'id'   => $category->id,
                                'name' => $category->name,
                            ];
                        }
                    }

                    return $data;
                }, $provider),
                'logo'        => url($provider->store->store_logo),
                'store_id' => $provider->store->id,
            ];
        }

        return success_return(['list' => $data]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }
}
